/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PodcastPanel.java
 *
 * Created on May 4, 2009, 8:42:05 AM
 */
package com.bff.slimserver.musicjukebox.ui;

import com.bff.slimserver.music.exceptions.PlaylistException;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.lib.actions.PlaylistAddFavoriteAction;
import com.bff.slimserver.musicjukebox.lib.actions.PlaylistInsertFavoriteAction;
import com.bff.slimserver.musicjukebox.lib.actions.PlaylistLoadFavoriteAction;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.slimserver.musicjukebox.ui.components.favorites.FavoritesInfoPanel;
import com.bff.slimserver.musicjukebox.ui.components.favorites.FavoritesTree;
import com.bff.slimserver.musicjukebox.ui.components.favorites.FavoritesTreeDnd;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.bff.slimserver.SlimFavoritePlugin;
import org.bff.slimserver.SlimPlayer;
import org.bff.slimserver.SlimPlaylist;
import org.bff.slimserver.events.FavoriteChangeEvent;
import org.bff.slimserver.events.FavoriteChangeListener;
import org.bff.slimserver.exception.SlimException;
import org.bff.slimserver.musicobjects.favorite.SlimFavorite;
import org.bff.slimserver.musicobjects.favorite.SlimFavoriteAudioDetails;
import org.bff.slimserver.musicobjects.favorite.SlimFavoriteItem;
import org.bff.slimserver.musicobjects.radio.SlimAvailableRadio;
import org.bff.slimserver.musicobjects.radio.SlimRadioItem;

/**
 *
 * @author Bill
 */
public class FavoritesPanel extends javax.swing.JPanel implements FavoriteChangeListener {

    private SlimPlaylist playlist;
    private SlimPlayer player;
    private SlimFavoritePlugin favoritePlugin;
    private JukeboxProperties jp;
    private boolean loadingItems;
    private static List<SlimAvailableRadio> loadedList;
    private static List<SlimRadioItem> loadedItemList;
    private boolean refreshing;

    /** Creates new form PodcastPanel */
    public FavoritesPanel() {
        jp = JukeboxProperties.getInstance();
        try {
            this.playlist = jp.getPlaylist();
            this.player = jp.getPlayer();
            this.favoritePlugin = jp.getFavoritesPlugin();
        } catch (PlaylistException ex) {
            Logger.getLogger(FavoritesPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SlimException ex) {
            Logger.getLogger(SongListTablePanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        initComponents();
        listFavorites();

        this.favoritePlugin.addFavoriteChangeListener(this);

        loadProgressBar.setVisible(false);
        loadDetailProgressBar.setVisible(false);
        btnAdd.setEnabled(false);
        btnRename.setEnabled(false);
        btnInsert.setEnabled(false);
        btnClearAndPlay.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel11 = new BJJPanel();
        jPanel2 = new BJJPanel();
        jPanel1 = new BJJPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        favoritesTree = new FavoritesTreeDnd();
        jPanel4 = new BJJPanel();
        loadProgressBar = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        jPanel12 = new BJJPanel();
        jPanel3 = new BJJPanel();
        jPanel5 = new BJJPanel();
        btnAdd = new javax.swing.JButton();
        btnInsert = new javax.swing.JButton();
        btnClearAndPlay = new javax.swing.JButton();
        jPanel7 = new BJJPanel();
        btnAddFolder = new javax.swing.JButton();
        btnDeleteFolder = new javax.swing.JButton();
        btnRename = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();
        jPanel13 = new BJJPanel();
        favoritesInfoPanel = new FavoritesInfoPanel(true);
        loadDetailProgressBar = new javax.swing.JProgressBar();

        setLayout(new java.awt.BorderLayout());

        jPanel11.setMinimumSize(new java.awt.Dimension(600, 125));
        jPanel11.setPreferredSize(new java.awt.Dimension(600, 424));
        jPanel11.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Radios"));
        jPanel1.setLayout(new java.awt.BorderLayout());

        favoritesTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                favoritesTreeValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(favoritesTree);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.BorderLayout());

        loadProgressBar.setIndeterminate(true);
        loadProgressBar.setString("Loading Favorites");
        loadProgressBar.setStringPainted(true);
        jPanel4.add(loadProgressBar, java.awt.BorderLayout.SOUTH);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jPanel4.add(jLabel1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel4, java.awt.BorderLayout.SOUTH);

        jPanel2.add(jPanel1, java.awt.BorderLayout.CENTER);

        jPanel11.add(jPanel2, java.awt.BorderLayout.CENTER);

        add(jPanel11, java.awt.BorderLayout.CENTER);

        jPanel12.setMinimumSize(new java.awt.Dimension(500, 81));
        jPanel12.setPreferredSize(new java.awt.Dimension(500, 533));
        jPanel12.setLayout(new java.awt.GridBagLayout());

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Playlist Actions"));

        btnAdd.setText("Add");
        btnAdd.setPreferredSize(new java.awt.Dimension(110, 25));
        jPanel5.add(btnAdd);

        btnInsert.setText("Insert");
        btnInsert.setPreferredSize(new java.awt.Dimension(110, 25));
        jPanel5.add(btnInsert);

        btnClearAndPlay.setText("Clear and Play");
        btnClearAndPlay.setPreferredSize(new java.awt.Dimension(110, 25));
        jPanel5.add(btnClearAndPlay);

        jPanel3.add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Favorite Actions"));

        btnAddFolder.setText("Add");
        btnAddFolder.setPreferredSize(new java.awt.Dimension(85, 25));
        btnAddFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddFolderActionPerformed(evt);
            }
        });
        jPanel7.add(btnAddFolder);

        btnDeleteFolder.setText("Delete");
        btnDeleteFolder.setPreferredSize(new java.awt.Dimension(85, 25));
        btnDeleteFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteFolderActionPerformed(evt);
            }
        });
        jPanel7.add(btnDeleteFolder);

        btnRename.setText("Rename");
        btnRename.setPreferredSize(new java.awt.Dimension(85, 25));
        btnRename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRenameActionPerformed(evt);
            }
        });
        jPanel7.add(btnRename);

        btnRefresh.setText("Refresh");
        btnRefresh.setPreferredSize(new java.awt.Dimension(85, 25));
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });
        jPanel7.add(btnRefresh);

        jPanel3.add(jPanel7, java.awt.BorderLayout.PAGE_START);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanel12.add(jPanel3, gridBagConstraints);

        jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Favorite Details"));
        jPanel13.setMinimumSize(new java.awt.Dimension(500, 493));
        jPanel13.setLayout(new java.awt.BorderLayout());

        favoritesInfoPanel.setMinimumSize(new java.awt.Dimension(500, 22));
        favoritesInfoPanel.setPreferredSize(new java.awt.Dimension(500, 474));
        jPanel13.add(favoritesInfoPanel, java.awt.BorderLayout.CENTER);

        loadDetailProgressBar.setIndeterminate(true);
        loadDetailProgressBar.setString("Loading Favorite Details");
        loadDetailProgressBar.setStringPainted(true);
        jPanel13.add(loadDetailProgressBar, java.awt.BorderLayout.SOUTH);

        jPanel12.add(jPanel13, new java.awt.GridBagConstraints());

        add(jPanel12, java.awt.BorderLayout.EAST);
    }// </editor-fold>//GEN-END:initComponents

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        listFavorites();
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void btnAddFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFolderActionPerformed
        String folder = JOptionPane.showInputDialog(this, "Please enter a folder name.");

        if (folder != null) {
            boolean success = false;
            try {
                success = getFavoritePlugin().addFolder(folder);
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (!success) {
                JOptionPane.showMessageDialog(this, "Could not create folder.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnAddFolderActionPerformed

    private void btnDeleteFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteFolderActionPerformed
        SlimFavorite selectedFav = getFavoritesTree().getSelectedFavorite();
        if (selectedFav != null) {
            try {
                getFavoritePlugin().deleteFavorite(selectedFav);
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_btnDeleteFolderActionPerformed

    private void favoritesTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_favoritesTreeValueChanged
        if (!refreshing) {
            try {
                if (getFavoritesTree().getSelectedFavorite().isAudio()) {
                    loadDetails();
                }

                if (getFavoritesTree().getSelectedFavorite() != null) {
                    btnRename.setEnabled(true);
                } else {
                    btnRename.setEnabled(false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_favoritesTreeValueChanged

    private void btnRenameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRenameActionPerformed
        String folder = JOptionPane.showInputDialog(this, "Please enter the new name.");

        if (folder != null) {
            try {
                getFavoritePlugin().renameFavorite(getFavoritesTree().getSelectedFavorite(), folder);
            } catch (SlimException ex) {
                Logger.getLogger(FavoritesPanel.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(
                        this, "Could not rename favorite.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnRenameActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnAddFolder;
    private javax.swing.JButton btnClearAndPlay;
    private javax.swing.JButton btnDeleteFolder;
    private javax.swing.JButton btnInsert;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnRename;
    private javax.swing.JPanel favoritesInfoPanel;
    private javax.swing.JTree favoritesTree;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JProgressBar loadDetailProgressBar;
    private javax.swing.JProgressBar loadProgressBar;
    // End of variables declaration//GEN-END:variables

    private FavoritesTree getFavoritesTree() {
        return (FavoritesTree) favoritesTree;
    }

    private void listFavorites() {
        loadedList = new ArrayList<SlimAvailableRadio>();
        loadedItemList =
                new ArrayList<SlimRadioItem>();

        new Thread(new Runnable() {

            @Override
            public void run() {
                loadProgressBar.setVisible(true);

                try {
                    try {
                        getFavoritesTree().listAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                        //new ErrorDialog(Utils.getParentComponent(getFavoritesTree()), "Could not get radio list.", e, false, false);
                    }

                } finally {
                    loadProgressBar.setVisible(false);
                }

            }
        }).start();
    }

    /**
     * @return the playlist
     */
    public SlimPlaylist getPlaylist() {
        return playlist;
    }

    /**
     * @param playlist the playlist to set
     */
    public void setPlaylist(SlimPlaylist playlist) {
        this.playlist = playlist;
    }

    /**
     * @return the podcaster
     */
    public SlimFavoritePlugin getFavoritePlugin() {
        return favoritePlugin;
    }

    /**
     * @param podcaster the podcaster to set
     */
    public void setFavoritePlugin(SlimFavoritePlugin favoritePlugin) {
        this.favoritePlugin = favoritePlugin;
    }

    /**
     * @return the player
     */
    public SlimPlayer getPlayer() {
        return player;
    }

    /**
     * @param player the player to set
     */
    public void setPlayer(SlimPlayer player) {
        this.player = player;
    }

    @Override
    public void favoritesChanged(FavoriteChangeEvent event) {
        listFavorites();
    }

    private FavoritesInfoPanel getFavoritesInfoPanel() {
        return (FavoritesInfoPanel) favoritesInfoPanel;
    }

    private void loadDetails() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                refreshing = true;
                try {
                    loadDetailProgressBar.setVisible(true);
                    favoritesTree.setEnabled(false);
                    SlimFavoriteAudioDetails details =
                            FavoritesTree.getDetailMap().get(getFavoritesTree().getSelectedFavorite());

                    if (details == null) {
                        details = getFavoritePlugin().getFavoriteAudioDetails(getFavoritesTree().getSelectedFavorite());
                        FavoritesTree.getDetailMap().put(getFavoritesTree().getSelectedFavorite(), details);
                    }

                    getFavoritesInfoPanel().setSongInfo(details);
                    btnAdd.setAction(new PlaylistAddFavoriteAction(playlist, details));
                    btnAdd.setEnabled(true);
                    btnAdd.setIcon(null);
                    btnInsert.setAction(new PlaylistInsertFavoriteAction(playlist, details));
                    btnInsert.setEnabled(true);
                    btnClearAndPlay.setAction(new PlaylistLoadFavoriteAction(playlist, details));
                    btnClearAndPlay.setEnabled(true);
                } catch (Exception ex) {
                    Logger.getLogger(PodcastPanel.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    refreshing = false;
                    loadDetailProgressBar.setVisible(false);
                    favoritesTree.setEnabled(true);
                }

            }
        }).start();
    }
    /*
    private void listItems() {
    loadProgressItems.setVisible(true);
    favoritesTree.setEnabled(false);
    podcastItemList.setEnabled(false);
    new Thread(new Runnable() {

    public void run() {
    try {
    loadingItems = true;

    if (getFavoritesTree().getSelectedRadio() != null) {
    List<SlimRadioAudioDetails> audioItems = new ArrayList<SlimRadioAudioDetails>();

    if (getFavoritesTree().getSelectedRadio() instanceof SlimRadioItem) {
    SlimRadioItem radio = (SlimRadioItem) getFavoritesTree().getSelectedRadio();
    boolean loaded = loadedItemList.contains(radio);

    if (!loaded) {
    getRadioPlugin().loadRadio(radio, radio.getCommand(), getPlayer());
    loadedItemList.add(radio);
    }

    for (SlimRadioItem item : radio.getRadioItems()) {
    if (item.isAudio()) {
    audioItems.add(getRadioPlugin().getAudioDetails(item, player));
    }
    }
    }

    if (getFavoritesTree().getSelectedRadio() instanceof SlimAvailableRadio) {
    SlimAvailableRadio radio = (SlimAvailableRadio) getFavoritesTree().getSelectedRadio();

    if (!radio.isSearch()) {
    jpSearch.setVisible(false);
    SlimRadioItem radioItem = getRadioPlugin().loadRadio(radio, getPlayer());

    boolean loaded = loadedList.contains(radio);

    if (!loaded) {
    getRadioPlugin().loadRadio(radioItem, radio.getCommand(), getPlayer());
    loadedList.add(radio);
    }

    for (SlimRadioItem item : radioItem.getRadioItems()) {
    if (item.isAudio()) {
    audioItems.add(getRadioPlugin().getAudioDetails(item, player));
    }
    }
    } else {
    jpSearch.setVisible(true);
    }
    }
    getRadioItemList().setRadioItems(audioItems);
    }
    } catch (SlimException ex) {
    Logger.getLogger(FavoritesPanel.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    podcastItemList.setEnabled(true);
    favoritesTree.setEnabled(true);
    loadProgressItems.setVisible(false);
    loadingItems = false;
    }
    }
    }).start();
    }
     */
}
